<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: silencc
 * @Date: 2020-08-14 09:05:20
 * @LastEditors: silencc
 * @LastEditTime: 2020-09-19 15:04:45
-->
<template>
  <a v-if="!data" :href="AliOssUrl" :download="AliOssUrl">
    <el-button
      style="margin-right:5px;"
      v-bind="$attrs"
      @click="handleDownLoad"
      :loading="downLoading"
    >
      <slot>下载</slot>
    </el-button>
  </a>
  <el-button
    v-else
    style="margin-right:5px;"
    v-bind="$attrs"
    @click="handleDownLoad"
    :loading="downLoading"
  >
    <slot>下载</slot>
  </el-button>
</template>

<script>
import { saveAs } from "file-saver"; // https://github.com/eligrey/FileSaver.js
import { ajax } from "../../lib";
import { request } from "@/utils/axios";
import { parseTime } from "../../lib/modules/date";
import { AliOssClient } from "../../lib/oss";
export default {
  name: "downloadFile",
  data() {
    return {
      downLoading: false,
      AliOssUrl: ""
    };
  },
  props: {
    url: {
      type: String,
      required: true,
      default: undefined
    },
    fileType: {
      type: String
      // required: true
    },
    data: {
      type: Object
    },
    method: {
      type: String
    },
    name: {
      type: String
      // required: true
    }
  },
  methods: {
    async handleDownLoad() {
      console.log(this.data, this.method, this.url, this.name);
      this.downLoading = true;
      // 阿里云请求下载资源   无method 和 data 传参
      if (!this.data && this.url) {
        let AliOssUrl = await AliOssClient.downLoadFile(this.name);
        this.AliOssUrl = AliOssUrl;
        setTimeout(() => {
          this.downLoading = false;
        }, 2000);

        // ajax({
        //   url: `${this.url}?t=${Date.now()}`,
        //   dataType: "blob",
        //   data: this.data,
        //   method: this.method,
        //   success: res => {
        //     const file = new File(
        //       [res],
        //       (this.name || `文件${Date.now()}`) +
        //         "-" +
        //         parseTime(0, "{y}-{m}-{d}") +
        //         `.${this.fileType}`,
        //       {
        //         type: "text/plain;charset=utf-8"
        //       }
        //     );
        //     saveAs(file);
        //   }
        // });
      } else {
        // 请求后台下载数据
        this.$Api
          .requestBlob({
            url: this.url,
            data: this.data,
            type: this.method
          })
          .then(async ([err, res]) => {
            const file = new File(
              [res],
              this.name || `文件${Date.now()}`,
              // + `.${this.fileType || ''}`,
              // "-" +
              // parseTime(0, "{y}-{m}-{d}")
              // +

              {
                type: "text/plain;charset=utf-8"
              }
            );
            await saveAs(file);
            setTimeout(() => {
              this.downLoading = false;
            }, 2000);
          });
      }
    }
  }
};
</script>
